import * as moment from 'moment';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import formDataService from "./formDataService";
import emplModel from '../model/empl2Model';
import visitMonthPlanModel from "../model/visitMonthPlanModel";
import consumerRecoderModel from "../model/consumerRecoderModel";
import dTalkApi from "../core/dTalkApi";
import addExportModel from '../model/addExportModel';
import storeInfoModel from '../model/storeInfoModel';
import storeRecoderModel from '../model/storeRecoderModel';

//暂时没有用的方法
class TempUseService{
    constructor(){}

    //获取当年的某一周的周一到周五的日期
    async getStartDateAndEndDateByWeeks(weeks:number){
        let week=0;
        if(weeks){
            week=weeks;
        }else{
           week= moment().weeks()
        }
        let element2=moment().isoWeeks(week).format('YYYY-MM-DD')
        console.log(element2,'<-------element2-------')
        let now = new Date(); //当前日期  
        let nowDayOfWeek = now.getDay(); //今天本周的第几天  
        let num=nowDayOfWeek-1
        // console.log(nowDayOfWeek,'<--------nowDayOfWeek----------') 
        let startDate=moment(element2).subtract(num,'days').format('YYYY-MM-DD');
        // console.log(startDate,'<----------startDate--------')   //当年的某一周的周一的日期
        let endDate=moment(startDate).add(4,'days').format('YYYY-MM-DD');
        // console.log(endDate,'<------------endDte========')   //当年的某一周的周五的日期
        return {startDate:startDate,endDate:endDate}
    }

    //领导查看一个月其所属的所有员工的统计数据列表----------已拜访的数据
    //leaderId:领导id month:月份
    async checkAllUserDataByMonth_2(leaderId: string, month: string) {
        console.log('领导的userid是:' + leaderId + '----月份:' + month);
        let json: any = [];
        let access_token=await dTalkApiUtil.getAccessToken();
        let data=await formDataService.getAuthrity(leaderId,access_token)
        let sonData=await formDataService.getsonDept(data.leaderDepts,true,access_token,[])
        let son_list = sonData.list;
        let arr:any=[]
        let data5=await emplModel.find({})
        if(data5.length>0){
            for (let index5 = 0; index5 < data5.length; index5++) {
                let element = data5[index5];
                arr.push(element.userId)
            }
        }
        //let employeeIdList = await visitMonthPlanModel.distinct("userId", { deptId: { $in: son_list } });
        let employeeIdList = await visitMonthPlanModel.distinct("userId", { deptId: { $in: son_list } });
        for (let index_ = 0; index_ < employeeIdList.length; index_++) {
            let employee = employeeIdList[index_];//员工id
            if(!arr.includes(employee)){
                continue;
            }
            if (employee == leaderId) {
                continue;
            } else {
                //查询员工姓名
                // let user = await dTalkApi.getUserDetail(employee);//员工信息
                let data=await visitMonthPlanModel.findOne({userId:employee,user:{$ne:null}})
                //统计数据
                // (1)统计一个员工每月已拜访现有客户的数量
                let visitedConsumerCount = await consumerRecoderModel.count({ planType: '现有客户', userid: employee, month: month,comment:2 });
                //(2)统计一个员工每月已拜访新客户的数量
                let visitedNewConsumerCount = await consumerRecoderModel.count({ planType: '新拓展客户', userid: employee, month: month,comment:2 });
                //(3)统计一个员工每月开会的次数
                let meetingCount = await visitMonthPlanModel.count({ meeting: '开会', userId: employee, month: month });
                //(4)统计一个员工每月休假的次数
                let restCount = await visitMonthPlanModel.count({ rest: '休假', userId: employee, month: month });
                
                
                
                
                json.push({
                    userid:employee,//员工的id(隐藏)
                    userName: data.user,
                    avatar: data.avatar,
                    // userName: user.name,
                    // avatar: user.avatar,
                    visitedCurrentConsumer: '拜访现有客户' + visitedConsumerCount + '次',
                    visitedNewConsumer: '拜访新客户' + visitedNewConsumerCount + '次',
                    rest: '请假' + restCount + '次',
                    meeting: '开会' + meetingCount + '次'
                })
            }
        }
        return json;
    }

    //添加addExporModel数据-----人均
    async addData2(){
        let access_token=await dTalkApiUtil.getAccessToken();
        let dateList=await formDataService.getDate2(1,13,'2018-06-01')
        // console.log(dateList,'dateList')
        let list_1=await visitMonthPlanModel.distinct('nation',{'$and':[{nation:{$ne:null}},{nation:{$ne:''}}]})
        let nation:any=''
        if(list_1.length>0){
            list_1.map(it=>{
                nation=it
            })
        }
        let a2=await visitMonthPlanModel.findOne({nation:nation,'$and':[{nationName:{$ne:null}},{nationName:{$ne:''}}]},{nationName:1,_id:0})
        let data=await dTalkApi.getSondepIdList(nation,false,access_token)
        let modelList=data.deptNames;   //模块
        // let proList=await visitMonthPlanModel.distinct('provinceName',{'$and':[{provinceName:{$ne:null}},{provinceName:{$ne:''}}]})
        let data2=await dTalkApi.getSondepIdList(nation,true,access_token)
        let areaList:any =[]
        for (let index = 0; index < data2.dept.length; index++) {
            let element = data2.dept[index];
            if(modelList.includes(element.name)){
                continue;
            }
            areaList.push(element)
        }
        console.log(areaList,'<------------------1',areaList.length)
        let data3=await dTalkApi.getUserList('63824079',access_token)
        let list_3:any[]=[]
        if(data3&&data3.userlist&&data3.userlist.length>0){
            for (let index_3 = 0; index_3 < data3.userlist.length; index_3++) {
                let empl = data3.userlist[index_3];
                list_3.push(empl.userid) 
            }
        }
        console.log(list_3,'????????????????')  
        if(areaList.length>0){
            for (let index_4 = 0; index_4 < areaList.length; index_4++) {
                let element = areaList[index_4];
                let id=element.id;
                let name=element.name
                let userList3:any[]=[]         
                if(id=='63824079'){
                    userList3=list_3
                }else{
                    userList3=await visitMonthPlanModel.distinct('userId',{'$or':[{areaName:name},{provinceName:name}],'$and':[{userId:{$ne:null}},{userId:{$ne:''}}]})
                }
                for (let a = 0; a < dateList.length; a++) {
                    let date = dateList[a];
                    let consumerCount_day=0
                    for (let b = 0; b < userList3.length; b++) {
                        let user_id = userList3[b];
                        let count =await formDataService.getCountConsumer_one_employeeDate1ToDate2(user_id,date,date)
                        consumerCount_day+=count;
                    }
                    let count:any=0;
                    if(userList3.length>0){
                        count=consumerCount_day/userList3.length
                    }
                   
                    let e=await addExportModel.update({name_id:id,name_:name,date_:date,
                        month:moment(date).format('MM'),
                        consumerCount_day:consumerCount_day,//日均
                        
                        comment:1
                    },{consumerCount_empl:count})
                    console.log(e,'e_e_e_e_e_e_',name,date,consumerCount_day)
                }

               
            }
        } 
    }

    //统计一个员工名下面的门店数量和客户数量
    async countTotalStoreOrConsumerByEmployeeId(userid: string) {
        let con_data=await consumerRecoderModel.distinct("consumerCode",{userid:userid,comment:1})
        let store_count=await storeInfoModel.count({consumerCode:{$in:con_data}})
        return {con_count:con_data.length,store_count:store_count}
    }
    
  //逐条显示一个员工的月拜访计划
    //userId:员工id month:月份
    async listMonthPlan(userId: string, month: string) {
        console.log('员工id:' + userId + ',月份是:' + month);
        let totalDay = 0;
        if (month == '03' || month == '05' || month == '07' || month == '08' || month == '10' || month == '012') {
            totalDay = 31;
        } else if (month == '04' || month == '06' || month == '09' || month == '11') {
            totalDay = 30;
        } else {
            totalDay = 28;
        };
        let dateList = [];
        for (let index = 0; index < totalDay; index++) {
            let date = '';
            if (index < 9) {
                date = '2018-' + month + '-0' + (index + 1);
            } else {
                date = '2018-' + month + '-' + (index + 1);
            }
            dateList[index] = date;
        }
        let json: any = {};//一个员工一个月的计划
        let json_body: any = [];
        let json_monthPlan_day: any = [];//一个员工一月的拜访计划(导入的计划与临时计划)
        for (let index = 0; index < dateList.length; index++) {
            let date_ = dateList[index];
            let json_leadPlan_day2: any = [];//一个员工一天的导入计划
            let json_temporaryPlan_day2: any = [];//一个员工一天的临时计划
            //(1)获取今日导入的计划数据
            let leadMonthPlanList = await visitMonthPlanModel.find({ userId: userId, planDate: date_, comment: 1 });
            if (leadMonthPlanList.length != 0) {
                //一天的导入计划数据
                for (let index_ = 0; index_ < leadMonthPlanList.length; index_++) {
                    let element = leadMonthPlanList[index_];
                    //获取拜访记录
                    let recoderDetail: any = '';
                    if (element.visitRecoder == '' || element.visitRecoder == null) {
                        recoderDetail = '';
                    } else {
                        if (element.plantype == '门店') {
                            recoderDetail = await storeRecoderModel.findById({ _id: element.visitRecoder });
                        } else {
                            recoderDetail = await consumerRecoderModel.findById({ _id: element.visitRecoder });
                        }
                    }
                    json_leadPlan_day2[index_] = {
                        id: element._id,//隐藏  mongodb数据库自建的_id
                        plantype: element.plantype,
                        customerType: element.customerType,//客户类型
                        consumerName: element.consumerName,//客户名称
                        consumerCode: element.consumerCode,//客户编码
                        planDate: element.planDate,//拜访日期
                        planStatus: element.planStatus,  //计划的状态
                        purpose: element.purpose,//拜访目的
                        comment: element.comment,
                        visitRecoder: recoderDetail
                    };
                }
            } else {
                // console.log(date_+'号无导入的拜访计划!!!!');
            }
            //一天的临时计划数据
            let temporaryPlanList = await visitMonthPlanModel.find({ userId: userId, planDate: date_, comment: 2 });
            //console.log(date_+'这一天的临时计划数据:['+temporaryPlanList+']'); 
            if (temporaryPlanList.length != 0) {
                // console.log(date_+'号有临时的拜访计划!!!!');
                for (let index_ = 0; index_ < temporaryPlanList.length; index_++) {
                    let item = temporaryPlanList[index_];
                    let recoderDetail: any = '';
                    if (item.visitRecoder == '' || item.visitRecoder == null) {
                        recoderDetail = '';
                    } else {
                        if (item.plantype == '门店') {
                            recoderDetail = await storeRecoderModel.findById({ _id: item.visitRecoder });
                        } else {
                            recoderDetail = await consumerRecoderModel.findById({ _id: item.visitRecoder });
                        }
                    }
                    // console.log(recoderDetail,'<--------',userId)
                    json_temporaryPlan_day2[index_] = {
                        id: item._id,//隐藏  mongodb数据库自建的_id
                        plantype: item.plantype,
                        customerType: item.customerType,//客户类型
                        consumerName: item.consumerName,//客户名称
                        consumerCode: item.consumerCode,//客户编码
                        planDate: item.planDate,//拜访日期
                        purpose: item.purpose,//拜访目的
                        planStatus: item.planStatus,  //计划的状态
                        comment: item.comment,
                        visitRecoder: recoderDetail
                    }
                }
            }
            json_monthPlan_day[index] = {
                date: date_,//日期
                leadPlan_day: json_leadPlan_day2, //一个员工一天的申请的导入计划
                temporaryPlan_day: json_temporaryPlan_day2//一个员工一天的临时计划
            }
        };
        //(二)Header部分:统计数据部分
        //一个员工一月计划拜访的条数
        let toalcount_month = await visitMonthPlanModel.count({ userId: userId, month: month, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' },{planStatus:'写好拜访记录'},{planStatus:'未写拜访记录'}] });
        //一个月已拜访门店的总数量
        let countStore = await storeRecoderModel.count({ userid: userId, month: month, planType: '门店' });
        // 一个月已拜访门店的门店达标的总数量 
        let reachStandard_store_count = await storeRecoderModel.count({ userid: userId, month: month, planType: '门店', isListStandard: true });
        let countConsumer = await consumerRecoderModel.count({ userid: userId, month: month, comment: 2 });
        let totalcount_month_visited = countStore + countConsumer;
        //门店达标率
        let storeRate_ = 0;
        if (countStore == 0) {
            storeRate_ = 0;
        } else {
            storeRate_ = (reachStandard_store_count / countStore) * 100;
        }
        let storeRate = storeRate_.toFixed(2);
        let consumerRate_ = 0;
        if (toalcount_month == 0) {
            consumerRate_ = 0;
        } else {
            consumerRate_ = (totalcount_month_visited / toalcount_month) * 100;
        }
        let consumerRate = consumerRate_.toFixed(2);
        json = {
            header: {
                one: '计划' + toalcount_month + '家,|达成' + totalcount_month_visited + '家',
                two: '客户拜访达成率' + consumerRate + '%',
                three: '已拜访门店' + countStore,
                four: '门店达标率' + storeRate + '%'
            },
            json_body: json_monthPlan_day
        }
        // console.log(json.json_body,'<--------------->')
        return json;
    } 

    //获取当月的员工的userid列表
    async getUserIdList(month: string) {
        let userIdList = await visitMonthPlanModel.distinct("userId", { month: month });
        return userIdList;
    }
  
    async isVisitedStoreOrConsmer(userid:string,month:string,planType:string,consumerCode:string,consumerName:string){
        //console.log(userid,'userId_',month,'mkonth_',planType,'planType_',consumerCode,'consumerCode_',consumerName,'consumerName_')
        let isVisited=false;
        let recoder:any='';
        if(planType=='门店'){
            let storeRecoder=await storeRecoderModel.findOne({userid:userid,month:month,storeCode:consumerCode,storeName:consumerName}) ;
            if(storeRecoder){
                console.log(userid+'本月已经拜访过该门店!!!')
                isVisited=true;
                recoder=storeRecoder;
            }
        }else{
            let conRecoder=await consumerRecoderModel.findOne({userid:userid,month:month,consumerCode:consumerCode,consumerName:consumerName,comment:2});
            if(conRecoder){
                console.log(userid+'本月已经拜访过该客户!!!')
                isVisited=true;
                recoder=conRecoder;
            }
        }
        let json={
            isVisited:isVisited,//是否拜访过客户或门店
            recoder:recoder
        }
        return json;
    }

    //获取模块负责人   
    async getModelManagers(){
        console.log('开始时间!!!!',moment().format('YYYY-MM-DD HH:mm:ss'))
        let access_token=await dTalkApiUtil.getAccessToken();
        let result= await dTalkApi.getRoles(access_token,100,0);
        //console.log(result,'<<<<<<<result')
        let directorArr:any[]=[];//主管列表
        if(result){
            let roles_arr:any[]=[];//
            result.list.map(item=>{
                //console.log(item,'item_item_item_')
                if(item.name=='模块'){
                    roles_arr=item.roles;
                }
            })
            //console.log(roles_arr,'<<<<<<<roles_arr')
            let director:any='';//模块负责人角色
            if(roles_arr.length){
                roles_arr.map(item2=>{
                    //console.log(item2,'<<<<<<item2')
                    if(item2.name=='模块负责人'){
                        director=item2;
                    }
                })
            }
           // console.log(director,'<===========director')
            let dataCache:any=[];
            let managerNames:any[]=[]
            if(director&&director.id){
                let size=130;
                let offset=0;
                let role_data=await dTalkApi.getRoleUsers(access_token,director.id,size,offset);
                console.log(role_data,'========role_data========')
                if(role_data&&role_data.list&&!role_data.hasMore){
                    role_data.list.map(ele=>{
                        if(!directorArr.includes(ele.userid)){
                            directorArr.push(ele.userid)
                        }
                        if(!managerNames.includes(ele.name)){
                            managerNames.push(ele.name)
                        }
                    });
                    for (const key in role_data.list) { 
                        if (role_data.list.hasOwnProperty(key)) {
                            const element = role_data.list[key];
                            dataCache.push(element)
                        }
                    }
                }
            }
            console.log(dataCache,'<=======模块负责人=============\n',managerNames,'<<<',directorArr.length)
            console.log('结束时间!!!',moment().format('YYYY-MM-DD HH:mm:ss'));
        }
        return directorArr;
    }




   

}
let tempUseService=new TempUseService();
export default tempUseService;